#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

long __some_very_private_data = 0;

__attribute__((constructor)) void ldload()
{
    printf("Hello in constructor\n");
    print_hello();
}

int print_hello()
{
    printf("Hello, world! [Called %ld times]\n"
          , __some_very_private_data ++
          );

    return 0;
}

void fd_to_file(int fd, const char * newout)
{
    if (NULL == newout)
    {
        fprintf(stderr
                , "Output path not specified. Bad shell code?\n"
                );
        return;
    }

    int newfd = open(newout, O_CREAT | O_APPEND | O_RDWR, 0666);

    if (-1 == newfd)
    {
        fprintf(stderr
                , "Couldn't output %s: %s\n"
                , newout
                , strerror(errno)
                );
        return;
    }

    fprintf(stderr
            , "dup2(%d, %d)\n"
            , newfd
            , fd
            );

    int rval = dup2(newfd, fd);

    if (rval == -1)
    {
        fprintf(stderr
                , "Couldn't perform dup: %s\n"
                , strerror(errno)
                );

        return;
    }
}
